package com.example.telesys.service.impl;

import com.example.telesys.mapper.UserMapper;
import com.example.telesys.pojo.User;
import com.example.telesys.pojo.UserExample;
import com.example.telesys.service.UserService;
import com.example.telesys.utils.Convert2MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Boolean verifyUserByEmail(String email) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andEmailEqualTo(email);
        return (userMapper.selectByExample(userExample).size() != 0) ? true : false;
    }

    @Override
    public User verifyUserByUsername(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> list = userMapper.selectByExample(userExample);
        return (list.size() == 0) ? null : list.get(0);
    }

    @Override
    @Transactional
    public int regist(User user) {
        user.setPassword(Convert2MD5.getMD5(user.getPassword()));
        return userMapper.insert(user);
    }

    @Override
    public int updatePassword(User user) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        return userMapper.updateByExampleSelective(user, userExample);
    }

    @Override
    public User selectUserByEmail(String email) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andEmailEqualTo(email);
        List<User> list = userMapper.selectByExample(userExample);
        if (list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

}
